import React, { useEffect } from "react";
import {
  HashRouter,
  Redirect,
  Route,
  Switch,
  withRouter
} from "react-router-dom";
import { hot } from "react-hot-loader/root";

let routes = [];

try {
  const context = require.context(`../pages`, true, /.*\/routes\.jsx?$/);
  context.keys().forEach((key) => {
    const route = context(key).default;
    routes = routes.concat(route);
  });
} catch (err) {
  console.warn(err.message);
}

// routes.push({
//   path: "/",
//   redirect: "/test",
// });

console.log(">>> routes: ", JSON.stringify(routes));

function SwitchRouterComponent(props) {
  useEffect(() => {
    // console.log('>>> Router Change: ', props.location);
  }, [props.location]);

  return (
    <React.Suspense fallback={<div />}>
      <Switch>
        {routes.map((route, index) =>
          route.redirect ? (
            <Redirect exact key={index} from={route.path} to={route.redirect} />
          ) : (
            <Route
              key={index}
              path={route.path}
              exact={true}
              component={route.component}
            />
          )
        )}
      </Switch>
    </React.Suspense>
  );
}

const WithRouterComponent = withRouter(SwitchRouterComponent);

/* eslint-disable */
function RouterComponent() {
  return (
    <HashRouter>
      <WithRouterComponent />
    </HashRouter>
  );
}

export default hot(RouterComponent);
